<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 打卡接口
 */
class Checkinoption extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['createcomplaint'];

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        $this->complainttype=model('admin/complaint/Type');
        $this->complaintcomplaints=model('admin/complaint/Complaints');
        $this->user=model('admin/User');
        $this->checkindata=model('admin/Checkindata');
        $this->visit=model('admin/customer/Visit');
    }

    /**
     * 获取打卡记录数据
     */
   public  function getcheckindata(){
       $result=getaccess_token();
       if ($result['ret']) {
           $json = (array)json_decode($result['msg'], true);
           $access_token=$json['access_token'];
       }else{
           $this->error("授权失败," . $result['msg']);
       }
      $useridList=$this->user->column('userid');
       $access_token=$json['access_token'];
       //获取客户列表
       $getcheckindataurl="https://qyapi.weixin.qq.com/cgi-bin/checkin/getcheckindata?access_token=".$access_token;//.$this->auth->userid;
       $params=['opencheckindatatype'=>3,'starttime'=>strtotime(date('Y-m-d',time())),'endtime'=>time(),'useridlist'=>$useridList];
       $getcheckindataList=  (array)json_decode($this->request($getcheckindataurl,json_encode($params)), true); // 获取打卡记录数据
     $dataall=[];
      foreach ($getcheckindataList['checkindata'] as $key=>$value){
          $where=[];
          $where['userid']=['=',$value['userid']];
          $where['checkin_type']=['=',$value['checkin_type']];
          $where['groupid']=['=',$value['groupid']];
          $where['checkin_time']=['between',[strtotime(date("Y-m-d",time())),time()]];

          if(!$this->checkindata->get($where)){
              $data=[
                'userid'=>$value['userid'],
                'groupname'=>$value['groupname'],
                'checkin_type'=>$value['checkin_type'],
                  'exception_type'=>$value['exception_type'],
                  'checkin_time'=>$value['checkin_time'],
                  'location_title'=>$value['location_title'],
                  'location_detail'=>$value['location_detail'],
                  'wifiname'=>$value['wifiname'],
                  'notes'=>$value['notes'],
                  'wifimac'=>$value['wifimac'],
                  'mediaids'=>$value['mediaids'],
                  'lat'=>$value['lat'],
                  'lng'=>$value['lng'],
                  'deviceid'=>$value['deviceid'],
                  'sch_checkin_time'=>!empty($value['sch_checkin_time']) ? $value['sch_checkin_time'] : 0,
                  'groupid'=>$value['groupid'],
                   'schedule_id'=>!empty($value['schedule_id']) ? $value['schedule_id'] : 0,
                  'timeline_id'=>!empty($value['timeline_id']) ? $value['timeline_id'] : 0,
              ];

              $dataall[]=$data;

          }

      }
      if(!empty($dataall)){
          $this->checkindata->saveAll($dataall);
      }
      $this->success('打卡记录数据导入成功');

   }



    /**
     * 获得最后一条打卡记录
     * @param $url
     * @param $params
     * @return bool|string
     */

    public function lastcheckindata(){
        $lastcheckindata=$this->checkindata->where('userid',$this->auth->userid)->where('exception_type','<>','未打卡')->limit(0,1)->order('checkin_time desc')->find();

        $this->success('OK',$lastcheckindata);
    }

    /**
     * 当日工作总结数据统计
     */

    public function todaycheckindata(){
        //今日打卡考勤
        $where['checkin_time']=['between',[strtotime(date('Y-m-d',time())),time()]];
        $where['checkin_type']=['in',['外出打卡','上班打卡']];
        $where['exception_type']=['<>','未打卡'];

        $data['kaoqinnum']=$this->checkindata->where('userid',$this->auth->userid)->where($where)->count();
        //今日拜访客户数量
        $visitwhere['sign_time']=['between',[strtotime(date('Y-m-d',time())),time()]];
        $data['visitnum']=$this->visit->where('user_id',$this->auth->id)->where($visitwhere)->count();


        //本月出差天数
        $goOutAccumulatenumwhere['checkin_time']=['between',[strtotime(date('Y-m-01',time())),time()]];
      //  $goOutAccumulatenumwhere['groupid']=['=',1];
        $goOutAccumulatenumwhere['checkin_type']=['in',['外出打卡']];
        $goOutAccumulatenumwhere['exception_type']=['<>','未打卡'];
        $data['goOutAccumulatenum']=$this->checkindata->where('userid',$this->auth->userid)->where($goOutAccumulatenumwhere)->count();

        //本月连续出差
        $lastcheckindata=$this->checkindata->where('userid',$this->auth->userid)->where('exception_type','<>','未打卡')->limit(0,1)->order('checkin_time desc')->find();

          if($lastcheckindata){

                  if($lastcheckindata->checkin_type!='外出打卡'){  //最后一次不是外出则找本月上次外出打卡时间


                      $where1['checkin_type']=['=','外出打卡'];
                      $where1['exception_type']=['<>','未打卡'];

                      $lastcheckinwaichudata=$this->checkindata->where('userid',$this->auth->userid)->where($where1)->limit(0,1)->order('checkin_time desc')->find();
                     if($lastcheckinwaichudata){
                         if($lastcheckinwaichudata->checkin_time>strtotime(date('Y-m-01',time()))){
                             $where2['userid']=['=',$this->auth->userid];
                             $where2['checkin_type']=['<>','外出打卡'];
                             $where2['exception_type']=['<>','未打卡'];
                             $lastcheckinzhengchangdata=$this->checkindata->where($where2)->find();
                             if($lastcheckinzhengchangdata['checkin_time']>strtotime(date('Y-m-01',time()))){
                                 $start_time=$lastcheckinzhengchangdata['checkin_time'];
                             }else{
                                 $start_time=strtotime(date('Y-m-01',time()));
                             }
                             $where3['userid']=['=',$this->auth->userid];
                             $where3['checkin_type']=['<>','外出打卡'];
                             $where3['exception_type']=['<>','未打卡'];
                             $where3['checkin_time']=['between',[$start_time,time()]];
                             $data['continuousnum']=$this->checkindata->where($where3)->count();
                         }else{

                             $data['continuousnum']=0;
                         }
                     }else{
                         $data['continuousnum']=0;
                     }



                  }else{ //如果上次是外出打卡，找最近的非外出记录


                      $where1['checkin_type']=['<>','外出打卡'];
                      $where1['exception_type']=['<>','未打卡'];
                      $lastcheckinzhengchangdata=$this->checkindata->where('userid',$this->auth->userid)->limit(0,1)->order('checkin_time desc')->find();
                      $where2['userid']=['=',$this->auth->userid];
                      $where2['checkin_type']=['in',['外出打卡']];
                      $where2['exception_type']=['<>','未打卡'];
                      if($lastcheckinzhengchangdata['checkin_time']>strtotime(date('Y-m-01',time()))){
                          $start_time=$lastcheckinzhengchangdata['checkin_time'];
                      }else{
                          $start_time=strtotime(date('Y-m-01',time()));
                      }
                      $where2['checkin_time']=[$start_time,time()];
                      $data['continuousnum']=$this->checkindata->where($where2)->count();


                  }
          }else{
              $data['continuousnum']=0;
          }

         $this->success('OK',$data);

    }
    public  function request($url, $params)
    {
        $ch = curl_init();

//$this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");

        $this_header = array('Content-Type: application/json; charset=utf-8');

        curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');

        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);

        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output = curl_exec($ch);
        curl_close($ch);

        return $output;
    }

}
